package com.naton.common.network

import io.reactivex.SingleObserver
import io.reactivex.disposables.Disposable

abstract class BaseObserver<T> : SingleObserver<BaseResponse<T>> {

    private var disposable : Disposable ? = null

    // 业务状态
    internal interface Status {
        companion object {
            const val STATUS_SUCCESS = 1 // 正常
            const val STATUS_FAIL = 0 // 失败
            const val STATUS_AUTH_FAIL = 1010101 // token缺少参数
            const val STATUS_TOKEN_LACK = 1010102 // 参数值非法
            const val STATUS_PARAMS_LACK = 1020101 // 内部错误
            const val STATUS_PARAMS_ERROR = 1030101 // 缺少token
            const val STATUS_INTERNAL_EXCEPTION = 1030102 // token无效
        }
    }

    override fun onSubscribe(d: Disposable) {
        disposable= d
    }

    /**
     * 取消订阅
     */
   open fun cancelSubscribe(){
        disposable?.dispose()
    }

    override fun onSuccess(response: BaseResponse<T>) {
        when(response.resultCode){
//             //成功
             Status.STATUS_SUCCESS -> onSuccessResult(response.data)
             //token无效
             Status.STATUS_INTERNAL_EXCEPTION ->{
                 //跳转到登录页面
                 onErrorResult(response.resultCode, ApiErrorModel(response.resultCode, "令牌失效"))
             }
             //业务失败
             Status.STATUS_FAIL, Status.STATUS_AUTH_FAIL, Status.STATUS_TOKEN_LACK, Status.STATUS_PARAMS_LACK, Status.STATUS_PARAMS_ERROR -> {
                 onErrorResult(response.resultCode, ApiErrorModel(response.resultCode, response.resultMsg ?:""))
             }
             else -> onErrorResult(
                 response.resultCode,
                 ApiErrorModel(response.resultCode, response.resultMsg)
             )
         }
    }

    override fun onError(e: Throwable) {
        onErrorResult(-1 , ApiErrorModel(-1 , e.message ?:""))
    }
    /**
     * 接口访问成功
     */
    abstract fun onSuccessResult(data: T)

    /**
     * 接口访问失败
     */
    abstract fun onErrorResult( statusCode : Int , apiErrorModel: ApiErrorModel)
}